package com.zmc.lostfound.search.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.zmc.lostfound.common.dto.UserBaseInfoDTO;
import com.zmc.lostfound.common.exception.MyException;
import com.zmc.lostfound.common.feign.AuthFeign;
import com.zmc.lostfound.common.utils.RegexUtil;
import com.zmc.lostfound.common.utils.Result;
import com.zmc.lostfound.search.service.UserSearchService;
import com.zmc.lostfound.search.vo.SearchResult;
import com.zmc.lostfound.search.vo.UserSearchVO;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.zmc.lostfound.common.constant.ElasticSearchConstant.ASC;
import static com.zmc.lostfound.common.constant.ElasticSearchConstant.USER_BASE_INFO_INDEX;
import static com.zmc.lostfound.common.constant.RegexConstant.*;

/**
 * @author ZMC
 * @description 用户信息搜索业务类
 * @email 2869581855@qq.com
 * @date 2023-07-05 15:17:37
 */
@Slf4j
@Service
public class UserSearchServiceImpl implements UserSearchService {

    private final RestHighLevelClient esRestClient;

    private final AuthFeign authFeign;

    public UserSearchServiceImpl(RestHighLevelClient esRestClient, AuthFeign authFeign) {
        this.esRestClient = esRestClient;
        this.authFeign = authFeign;
    }

    /**
     * 多条件搜索用户基本信息
     *
     * @param userSearchVO 用户搜索参数请求体
     * @return SearchResult
     */
    @Override
    public SearchResult searchBaseInfo(UserSearchVO userSearchVO) {
        // 1.创建SearchRequest
        SearchRequest request = new SearchRequest(USER_BASE_INFO_INDEX);
        SearchSourceBuilder sourceBuilder = request.source();
        // 2.封装DSL查询语句
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        String keyword = userSearchVO.getKeyword();
        // 2.1 should查询
        if (StrUtil.isNotBlank(keyword)) {
            HighlightBuilder highlightBuilder = new HighlightBuilder().requireFieldMatch(false);
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            // 2.1.1对昵称进行全文检索
            boolQuery.should(QueryBuilders.matchQuery("nickname", keyword));
            // 设置昵称高亮
            highlightBuilder.field("nickname");
            // 2.1.2对手机号进行前缀匹配
            if (!RegexUtil.mismatch(keyword, PHONE_PREFIX_REGEX)) {
                boolQuery.should(QueryBuilders.wildcardQuery("phone", keyword + "*"));
                // 设置手机号高亮
                highlightBuilder.field("phone");
            }
            // 2.1.3对邮箱进行前缀匹配
            if (!RegexUtil.mismatch(keyword, NOT_CHINESE_REGEX)) {
                boolQuery.should(QueryBuilders.wildcardQuery("qqEmail", keyword + "*"));
                // 设置邮箱高亮
                highlightBuilder.field("qqEmail");
            }
            // 2.1.4对用户id进行精确查询
            if (!RegexUtil.mismatch(keyword, NUM_REGEX)) {
                boolQuery.should(QueryBuilders.termsQuery("id", keyword));
            }
            // 2.1.5设置高亮
            sourceBuilder.highlighter(highlightBuilder);
            // 2.1.6以上should(或)子查询条件至少匹配一个
            boolQuery.minimumShouldMatch(1);
        } else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        // 2.2 条件过滤
        // 2.2.1 精确查询---用户性别
        Integer sex = userSearchVO.getSex();
        if (sex != null) {
            boolQuery.filter(QueryBuilders.termQuery("sex", sex));
        }
        // 2.2.2 精确查询---是否封号
        Integer disableStatus = userSearchVO.getDisableStatus();
        if (disableStatus != null) {
            boolQuery.filter(QueryBuilders.termQuery("disableStatus", disableStatus));
        }
        // 2.3添加封装好的DSL查询语句
        sourceBuilder.query(boolQuery);
        // 2.4排序
        // 2.4.1按id排序
        String sortByUserId = userSearchVO.getSortByUserId();
        if (sortByUserId != null) {
            SortOrder sortOrder = ASC.equals(sortByUserId) ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort("id", sortOrder);
        }
        // 2.4.2按注册时间排序
        String sortByGmtCreate = userSearchVO.getSortByGmtCreate();
        if (sortByGmtCreate != null) {
            SortOrder sortOrder = ASC.equals(sortByGmtCreate) ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort("gmtCreate", sortOrder);
        }
        // 2.5分页
        Integer pageNo = userSearchVO.getPageNo();
        Integer pageSize = userSearchVO.getPageSize();
        sourceBuilder.from((pageNo - 1) * pageSize);
        sourceBuilder.size(pageSize);
        // 3.发送查询请求，解析响应结果到PageResult并返回
        System.err.println("DSL查询语句 = " + sourceBuilder.toString());
        SearchResult searchResult = new SearchResult();
        searchResult.setPageNo(pageNo);
        searchResult.setPageSize(pageSize);
        searchResult.setTotalCount(0);
        searchResult.setTotalPage(0);
        try {
            // 3.1向ES发送查询请求
            SearchResponse response = esRestClient.search(request, RequestOptions.DEFAULT);
            // 3.2解析ES响应结果
            this.handleResponse(response, searchResult);
        } catch (Exception e) {
            log.error("ES检索用户基本信息失败: " + e.getMessage(), e);
            MyException.throwException("ES检索用户基本信息失败: " + e.getMessage());
        }
        return searchResult;
    }

    /**
     * 解析查询结果并封装到SearchResult
     *
     * @param response     ES查询结果
     * @param searchResult 商品检索结果
     */
    private void handleResponse(SearchResponse response, SearchResult searchResult) {
        if (response == null || searchResult == null) {
            return;
        }
        SearchHits searchHits = response.getHits();
        // 1.获取查询总记录数
        long totalCount = searchHits.getTotalHits().value;
        if (totalCount <= 0) {
            return;
        }
        // 1.1设置总记录数
        searchResult.setTotalCount((int) (totalCount));
        // 1.2计算总页数
        searchResult.calculateTotalPage();
        // 2.获取查询的用户信息
        SearchHit[] hits = searchHits.getHits();
        List<UserBaseInfoDTO> userBaseInfoDTOList = null;
        if (hits != null && hits.length > 0) {
            userBaseInfoDTOList = new ArrayList<>(hits.length);
            for (SearchHit hit : hits) {
                String json = hit.getSourceAsString();
                // 2.1反序列化
                UserBaseInfoDTO userBaseInfoDTO = JSONUtil.toBean(json, UserBaseInfoDTO.class);
                // 2.2获取高亮结果
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (CollectionUtil.isNotEmpty(highlightFields)) {
                    // 根据字段名称获取高亮结果
                    HighlightField nicknameField = highlightFields.get("nickname");
                    if (nicknameField != null) {
                        // 设置高亮数据
                        String nickname = nicknameField.getFragments()[0].string();
                        userBaseInfoDTO.setNickname(nickname);
                    }
                    HighlightField phoneField = highlightFields.get("phone");
                    if (phoneField != null) {
                        String phone = phoneField.getFragments()[0].string();
                        userBaseInfoDTO.setPhone(phone);
                    }
                    HighlightField qqEmailField = highlightFields.get("qqEmail");
                    if (qqEmailField != null) {
                        String qqEmail = qqEmailField.getFragments()[0].string();
                        userBaseInfoDTO.setQqEmail(qqEmail);
                    }
                }
                userBaseInfoDTOList.add(userBaseInfoDTO);
            }
        }
        searchResult.setDataList(userBaseInfoDTOList);
    }

    /**
     * 根据id新增/修改ES的user_base_info索引库的文档
     *
     * @param id 文档id
     */
    @Override
    public void saveById(Long id) {
        try {
            // 根据id查询从数据库查询UserBaseInfo
            Result result = authFeign.queryBaseInfoById(id);
            if (result != null && HttpStatus.HTTP_OK == result.getCode()) {
                UserBaseInfoDTO userBaseInfoDTO = result.getBean("userBaseInfoVO", UserBaseInfoDTO.class);
                // 创建IndexRequest对象
                IndexRequest request = new IndexRequest(USER_BASE_INFO_INDEX).id(userBaseInfoDTO.getId().toString());
                // 序列化
                request.source(JSONUtil.toJsonStr(userBaseInfoDTO), XContentType.JSON);
                // 发送请求
                esRestClient.index(request, RequestOptions.DEFAULT);
            } else if (result != null) {
                log.error("新增/修改user_base_info索引库的文档" + id + "失败: " + result.getMessage());
                MyException.throwException("新增/修改user_base_info索引库的文档" + id + "失败: " + result.getMessage());
            } else {
                log.error("新增/修改user_base_info索引库的文档" + id + "失败");
                MyException.throwException("新增/修改user_base_info索引库的文档" + id + "失败");
            }
        } catch (Exception e) {
            log.error("新增/修改user_base_info索引库的文档" + id + "失败: " + e.getMessage(), e);
            MyException.throwException("新增/修改user_base_info索引库的文档" + id + "失败: " + e.getMessage());
        }
    }

    /**
     * 根据id删除ES的user_base_info索引库的文档
     *
     * @param id 文档id
     */
    @Override
    public void deleteById(Long id) {
        try {
            // 1.创建DeleteRequest对象
            DeleteRequest request = new DeleteRequest(USER_BASE_INFO_INDEX, String.valueOf(id));
            // 2.发送请求
            esRestClient.delete(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            log.error("删除user_base_info索引库的文档" + id + "失败: " + e.getMessage(), e);
            MyException.throwException("删除user_base_info索引库的文档" + id + "失败: " + e.getMessage());
        }
    }

}
